//
//  LSCityChooseView.m
//  LSCityChoose
//
//  Created by lisonglin on 26/04/2017.
//  Copyright © 2017 lisonglin. All rights reserved.
//

#import "LSCityChooseView.h"
#import "EMCityDataManager.h"

#define PICKERHEIGHT 216
#define BGHEIGHT     264

#define KEY_WINDOW_HEIGHT [UIApplication sharedApplication].keyWindow.frame.size.height

@interface LSCityChooseView ()<UIPickerViewDelegate,UIPickerViewDataSource>
@property(nonatomic, copy) SureHandle selectedBlock;
@property (nonatomic,copy) CancelHandle cancelBlock;
/**
 pickerView
 */
@property(nonatomic, strong) UIPickerView * pickerView;
/**
 bgView
 */
@property(nonatomic, strong) UIView * bgView;

/**
 toolBar
 */
@property(nonatomic, strong) UIView * toolBar;

/**
 取消按钮
 */
@property(nonatomic, strong) UIButton * cancleBtn;

/**
 确定按钮
 */
@property(nonatomic, strong) UIButton * sureBtn;


/**
 省
 */
@property(nonatomic, strong) NSArray * provinceArray;
@property(nonatomic, strong) NSArray * provinceDataArray;

/**
 市
 */
@property(nonatomic, strong) NSArray * cityArray;
@property(nonatomic, strong) NSArray * cityDataArray;
/**
 区
 */
@property(nonatomic, strong) NSArray * areaArray;
@property(nonatomic, strong) NSArray * areaDataArray;
/**
 所有数据
 */
@property(nonatomic, strong) NSArray * dataSource;

/**
 记录省选中的位置
 */
@property(nonatomic, assign) NSInteger selected;

/**
 选中的省
 */
@property(nonatomic, copy) NSString * provinceStr;
@property(nonatomic, copy) NSString * provinceID;
/**
 选中的市
 */
@property(nonatomic, copy) NSString * cityStr;
@property(nonatomic, copy) NSString * cityID;
/**
 选中的区
 */
@property(nonatomic, copy) NSString * areaStr;
@property(nonatomic, copy) NSString * areaID;

@end

@implementation LSCityChooseView

#pragma mark -- lazy

- (UIButton *)cancleBtn
{
    if (!_cancleBtn) {
        _cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancleBtn.frame = CGRectMake(10, 5, 50, BGHEIGHT - PICKERHEIGHT - 10);
        [_cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancleBtn setTitleColor:[UIColor colorWithRed:(40 / 255.0) green:(191 / 255.0) blue:(169 / 255.0) alpha:1.000] forState:UIControlStateNormal];
        
        _cancleBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_cancleBtn addTarget:self action:@selector(cancleBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancleBtn;
}

- (UIButton *)sureBtn
{
    if (!_sureBtn) {
        _sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _sureBtn.frame = CGRectMake(self.frame.size.width - 60, 5, 50, BGHEIGHT - PICKERHEIGHT - 10);
        [_sureBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_sureBtn setTitleColor:[UIColor colorWithRed:(40.0 / 255.0) green:(191.0 / 255.0) blue:(169.0 / 255.0) alpha:1.000] forState:UIControlStateNormal];
        
        _sureBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_sureBtn addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sureBtn;
}

- (UIView *)toolBar
{
    if (!_toolBar) {
        _toolBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, BGHEIGHT - PICKERHEIGHT)];
        _toolBar.backgroundColor = [UIColor whiteColor];
        UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(_toolBar.frame) - 1, CGRectGetWidth(_toolBar.frame), 0.5)];
        v.backgroundColor = [UIColor colorWithRed:(215 / 255.0) green:(215 / 255.0) blue:(215 / 255.0) alpha:1.000];
        [_toolBar addSubview:v];
    }
    return _toolBar;
}
- (UIView *)bgView
{
    if (!_bgView) {
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, self.frame.size.height - BGHEIGHT , self.frame.size.width, BGHEIGHT)];
        
        _bgView.backgroundColor = [UIColor whiteColor];
    }
    return _bgView;
}

- (NSArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSArray array];
    }
    return _dataSource;
}

- (UIPickerView *)pickerView
{
    if (!_pickerView) {
        _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, BGHEIGHT - PICKERHEIGHT, self.frame.size.width, PICKERHEIGHT)];
        _pickerView.showsSelectionIndicator = YES;
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
    }
    return _pickerView;
}

- (NSArray *)provinceArray
{
    if (!_provinceArray) {
        _provinceArray = [NSArray array];
    }
    return _provinceArray;
}

- (NSArray *)cityArray
{
    if (!_cityArray) {
        _cityArray = [NSArray array];
    }
    return _cityArray;
}

- (NSArray *)areaArray
{
    if (!_areaArray) {
        _areaArray = [NSArray array];
    }
    return _areaArray;
}

#pragma mark -- init
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.selected = 0;
        
        [self initSuViews];
        [self loadDatas];
    }
    return self;
}

#pragma mark -- 从plist里面读数据
- (void)loadDatas
{
    NSString * path = [[NSBundle mainBundle] pathForResource:@"BKLHealth_CityList" ofType:@"plist"];
    self.dataSource = [NSArray arrayWithContentsOfFile:path];
    
    NSMutableArray * tempArray = [NSMutableArray array];
    for (NSDictionary * tempDic in self.dataSource) {
        
        for (int i = 0; i < tempDic.allKeys.count; i ++) {
            [tempArray addObject:tempDic.allKeys[i]];
        }
        
    }
    //省
    [[EMCityDataManager shareManager] getResultListFromKey:EMCityDataManagerSearchKeyLevel withValue:@"1" compltion:^(BOOL success, NSArray *dataArray) {
        if (success) {
            self.provinceDataArray = dataArray;
            NSMutableArray *arrM = [NSMutableArray array];
            for (int i = 0; i < dataArray.count; i ++) {
                [arrM addObject:[[dataArray objectAtIndex:i] objectForKey:@"name"]];
            }
            self.provinceArray = arrM;
            self.provinceStr = self.provinceArray[0];
            self.provinceID = [[dataArray objectAtIndex:0] objectForKey:@"ID"];
            // 省市区默认是北京
            [[EMCityDataManager shareManager] getResultListFromKey:EMCityDataManagerSearchKeyParentID withValue:@"2" compltion:^(BOOL success, NSArray *dataArray) {
                if (success) {
                    NSMutableArray *arrM = [NSMutableArray array];
                    for (int i = 0; i < dataArray.count; i ++) {
                        [arrM addObject:[[dataArray objectAtIndex:i] objectForKey:@"name"]];
                    }
                    self.cityArray = arrM;
                    self.cityDataArray = dataArray;
                    self.cityStr = self.cityArray[0];
                    self.cityID = [[dataArray objectAtIndex:0] objectForKey:@"ID"];
                    
                    [[EMCityDataManager shareManager] getResultListFromKey:EMCityDataManagerSearchKeyParentID withValue:[[dataArray objectAtIndex:0] objectForKey:@"ID"] compltion:^(BOOL success, NSArray *dataArray) {
                        if (success) {
                            NSMutableArray *arrM = [NSMutableArray array];
                            for (int i = 0; i < dataArray.count; i ++) {
                                [arrM addObject:[[dataArray objectAtIndex:i] objectForKey:@"name"]];
                            }
                            self.areaArray = arrM;
                            self.areaDataArray = dataArray;
                            self.areaStr = self.areaArray[0];
                            self.areaID = [[dataArray objectAtIndex:0] objectForKey:@"ID"];
                        }
                    }];
                }
            }];
        }
    }];
}

- (NSArray *)getAreaNamesFromCity:(NSInteger)row
{
    NSDictionary * tempDic = [self.dataSource[self.selected] objectForKey:self.provinceArray[self.selected]];
    NSArray * array = [NSArray array];
    
    NSDictionary * dic = tempDic.allValues[row];
    array = [dic objectForKey:self.cityArray[row]];
    
    return array;
}

- (NSArray *)getCityNamesFromProvince:(NSInteger)row
{
    NSDictionary * tempDic = [self.dataSource[row] objectForKey:self.provinceArray[row]];
    NSMutableArray * cityArray = [NSMutableArray array];
    for (NSDictionary * valueDic in tempDic.allValues) {
        
        for (int i = 0; i < valueDic.allKeys.count; i ++) {
            [cityArray addObject:valueDic.allKeys[i]];
        }
    }
    return [cityArray copy];
}


#pragma mark -- loadSubViews
- (void)initSuViews
{
    self.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.bgView];
    [self.bgView addSubview:self.toolBar];
    [self.bgView addSubview:self.pickerView];
    [self.toolBar addSubview:self.cancleBtn];
    [self.toolBar addSubview:self.sureBtn];
    
}

- (void)clearSpearatorLine
{
    for (UIView *subView1 in self.subviews)
    {
        if ([subView1 isKindOfClass:[UIPickerView class]])//取出UIPickerView
        {
            for(UIView *subView2 in subView1.subviews)
            {
                if (subView2.frame.size.height < 1)//取出分割线view
                {
                    subView2.backgroundColor = [UIColor colorWithRed:0.867 green:0.867 blue:0.867 alpha:1.000];
                }
            }
        }
    }
}


#pragma mark -- UIPickerView
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        return self.provinceArray.count;
    }else if (component == 1){
        return self.cityArray.count;
    }else if (component == 2){
        return self.areaArray.count;
    }
    return 0;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width / 3, 10)];
    label.adjustsFontSizeToFitWidth = YES;
    label.textAlignment = NSTextAlignmentCenter;
    if (component == 0) {
        label.text = self.provinceArray[row];
    }else if (component == 1){
        label.text = self.cityArray[row];
    }else if (component == 2){
        label.text = self.areaArray[row];
    }
    
    [pickerView.subviews objectAtIndex:1].backgroundColor = [UIColor colorWithRed:200/255.0 green:200/255.0 blue:200/255.0 alpha:1];
    [pickerView.subviews objectAtIndex:2].backgroundColor = [UIColor colorWithRed:200/255.0 green:200/255.0 blue:200/255.0 alpha:1];
    
    return label;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {//选择省
        self.selected = row;
        NSString *parentID = [[self.provinceDataArray objectAtIndex:row] objectForKey:@"ID"];
        [[EMCityDataManager shareManager] getResultListFromKey:EMCityDataManagerSearchKeyParentID withValue:parentID compltion:^(BOOL success, NSArray *dataArray) {
            NSMutableArray *arrM = [NSMutableArray array];
            for (int i = 0; i < dataArray.count; i ++) {
                [arrM addObject:[[dataArray objectAtIndex:i] objectForKey:@"name"]];
            }
            self.cityArray = arrM;
            self.cityDataArray = dataArray;
            
            [[EMCityDataManager shareManager] getResultListFromKey:EMCityDataManagerSearchKeyParentID withValue:[[dataArray objectAtIndex:0] objectForKey:@"ID"] compltion:^(BOOL success, NSArray *dataArray) {
                if (success) {
                    NSMutableArray *arrM = [NSMutableArray array];
                    for (int i = 0; i < dataArray.count; i ++) {
                        [arrM addObject:[[dataArray objectAtIndex:i] objectForKey:@"name"]];
                    }
                    
                    self.areaArray = arrM;
                    self.areaDataArray = dataArray;
                    
                    [self.pickerView reloadComponent:1];
                    [self.pickerView selectRow:0 inComponent:1 animated:YES];
                    [self.pickerView reloadComponent:2];
                    [self.pickerView selectRow:0 inComponent:2 animated:YES];
                    
                    self.provinceStr = self.provinceArray[row];
                    self.provinceID = [[self.provinceDataArray objectAtIndex:row] objectForKey:@"ID"];
                    self.cityStr = self.cityArray[0];
                    self.cityID = [[self.cityDataArray objectAtIndex:0] objectForKey:@"ID"];
                    self.areaStr = self.areaArray[0];
                    self.areaID = [[self.areaDataArray objectAtIndex:0] objectForKey:@"ID"];
                }
            }];
        }];
        
    }else if (component == 1){//选择市
        NSString *parentID = [[self.cityDataArray objectAtIndex:row] objectForKey:@"ID"];
        [[EMCityDataManager shareManager] getResultListFromKey:EMCityDataManagerSearchKeyParentID withValue:parentID compltion:^(BOOL success, NSArray *dataArray) {
            if (success) {
                NSMutableArray *arrM = [NSMutableArray array];
                for (int i = 0; i < dataArray.count; i ++) {
                    [arrM addObject:[[dataArray objectAtIndex:i] objectForKey:@"name"]];
                }
                self.areaArray = arrM;
                self.areaDataArray = dataArray;
                
                [self.pickerView reloadComponent:2];
                [self.pickerView selectRow:0 inComponent:2 animated:YES];
                self.cityStr = self.cityArray[row];
                self.cityID = [[self.cityDataArray objectAtIndex:row] objectForKey:@"ID"];
                self.areaStr = self.areaArray[0];
                self.areaID = [[self.areaDataArray objectAtIndex:0] objectForKey:@"ID"];
            }
        }];
        
        
    }else if (component == 2){//选择区
        self.areaStr = self.areaArray[row];
        self.areaID = [[self.areaDataArray objectAtIndex:row] objectForKey:@"ID"];
    }
}


//- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
//{
//    return 40.0;
//}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}


#pragma mark -- Button
- (void)cancleBtnClick {
    
    if (self.cancelBlock) {
        self.cancelBlock();
    }
    
}

- (void)sureBtnClick
{
    
    if (self.selectedBlock != nil) {
        self.selectedBlock(self.provinceStr, self.provinceID, self.cityStr, self.cityID, self.areaStr, self.areaID);
    }
}

#pragma mark - Block handler
- (void)sure:(SureHandle)sureHandler {
    self.selectedBlock = sureHandler;
}

- (void)cancel:(CancelHandle)cancelHandler {
    self.cancelBlock = cancelHandler;
}

@end

